package com.zwh.modules.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 使用RestTemplate作为负载均衡进行服务远程访问
 *
 * @author zwh
 * @date 2021/7/9 13:18
 **/
@RestController
public class DiscoveryController {

    /**
     * spring框架的负载均衡工具调用远程服务
     */
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;


    /**
     * 获取服务名对应的（ip+port）列表
     *
     * @param serviceName
     * @return
     */
    @GetMapping("/discovery/{serviceName}")
    public ResponseEntity<List<String>> discovery(@PathVariable String serviceName) {
        /**
         * 通过服务的ID或者名称得到服务的实例列表
         */
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);

        if (instances == null || instances.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        List<String> service = new ArrayList<>(instances.size());
        instances.forEach(instance -> {
            service.add(instance.getHost() + ":" + instance.getPort());
            ;
        });
        return ResponseEntity.ok(service);
    }

    /**
     * 调用nacos的负载均衡算法
     * 使用 restTemplate调用提供者。 使用 （http:// 服务名 + 接口）进行服务调用
     *
     * @param message
     * @return
     */
    @GetMapping("/rpcv4/{message}")
    public ResponseEntity<String> rpcv4(@PathVariable("message") String message) {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "http://service-provider/echo/{message}",
                String.class,
                message);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return ResponseEntity.ok(String.format("远程调用成功，结果为" + responseEntity.getBody()));
        }
        return ResponseEntity.badRequest().body("远程调用失败");
    }


}
